import sys
import os
# 将项目根目录添加到Python路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# 导入FastMCP框架的核心模块
from fastmcp import FastMCP
# 导入SeaTable的API
from seatable_api import Base, context, Account
from seatable_api.constants import ColumnTypes
# 导入配置管理器
from config.config_manager import get_api_key, save_config

# 初始化FastMCP服务器实例
mcp = FastMCP("SeaTable_Demo 🚀")    # 参数说明：服务器名称（用于标识服务，支持emoji）

# 全局API令牌
GLOBAL_API_TOKEN = None

def authenticate_seatable(api_token=None):
    """
    使用提供的API令牌验证SeaTable
    """
    token = api_token or GLOBAL_API_TOKEN
    if not token:
        raise ValueError("API令牌未提供，请在配置文件中设置或显式传递")
        
    server_url = context.server_url or 'https://cloud.seatable.cn'
    
    base = Base(token, server_url)
    base.auth()
    return base


@mcp.tool
def get_metadata(api_token: str = None) -> dict:
    """
    获取 base 的元数据信息
    Args:
        api_token: SeaTable API令牌，可选，未提供时使用全局配置
    Returns:
        包含表格结构、视图、脚本等元数据的字典
    """
    base = authenticate_seatable(api_token)
    return base.get_metadata()

@mcp.tool
def list_tables(api_token: str = None) -> list:
    """
    获取 base 中的子表列表
    Args:
        api_token: SeaTable API令牌，可选，未提供时使用全局配置
    Returns:
        子表列表
    """
    base = authenticate_seatable(api_token)
    return base.list_tables()

@mcp.tool
def batch_table_operations(operation: str, tables_data: list, lang: str = 'en', api_token: str = None) -> dict:
    """
    子表格批量操作函数，可执行多种批量表格操作
    
    Args:
        operation: 要执行的操作类型，支持以下几种:
            - 'get': 获取多个表的信息
            - 'add': 批量添加表
            - 'rename': 批量重命名表
            - 'delete': 批量删除表
        tables_data: 表格数据，根据不同操作有不同格式:
            - 'get': 字符串或字符串列表，表示要获取的表名
            - 'add': 可以是表名字符串列表，或包含 {'name': '表名', 'lang': '语言'} 的字典列表
            - 'rename': 字典列表，每个字典包含 {'old_name': '原表名', 'new_name': '新表名'} 
            - 'delete': 字符串列表，表示要删除的表名
        lang: 创建表时使用的语言，默认 'en'，可选 'zh-cn'，仅在 operation='add' 时有效
        api_token: SeaTable API令牌，可选，未提供时使用全局配置
    
    Returns:
        操作结果，具体结构根据操作类型而定
    
    Examples:
        # 获取单个表信息
        table_info = batch_table_operations('get', '表1')
        
        # 获取多个表信息
        tables_info = batch_table_operations('get', ['表1', '表2', '表3'])
        
        # 添加单个表
        add_result = batch_table_operations('add', '新表1', lang='zh-cn')
        
        # 批量添加表
        add_result = batch_table_operations('add', ['新表1', '新表2'], lang='zh-cn')
        # 或者使用详细配置
        add_result = batch_table_operations('add', [
            {'name': '新表1', 'lang': 'zh-cn'},
            {'name': '新表2', 'lang': 'en'}
        ])
        
        # 重命名单个表
        rename_result = batch_table_operations('rename', [
            {'old_name': '表1', 'new_name': '新表1'}
        ])
        
        # 批量重命名表
        rename_result = batch_table_operations('rename', [
            {'old_name': '表1', 'new_name': '新表1'},
            {'old_name': '表2', 'new_name': '新表2'}
        ])
        
        # 删除单个表
        delete_result = batch_table_operations('delete', '表1')
        
        # 批量删除表
        delete_result = batch_table_operations('delete', ['表1', '表2'])
    """
    base = authenticate_seatable(api_token)
    
    # 标准化输入：如果tables_data是字符串，转换为列表
    if isinstance(tables_data, str):
        tables_data = [tables_data]
    
    # 根据操作类型分发不同的处理逻辑
    if operation == 'get':
        results = {}
        for table_name in tables_data:
            try:
                table_info = base.get_table_by_name(table_name)
                results[table_name] = {
                    "status": "success",
                    "info": table_info
                }
            except Exception as e:
                results[table_name] = {
                    "status": "error",
                    "message": str(e)
                }
        return results
    
    elif operation == 'add':
        results = []
        for table_data in tables_data:
            try:
                # 处理不同的输入格式
                if isinstance(table_data, str):
                    table_name = table_data
                    table_lang = lang
                elif isinstance(table_data, dict):
                    table_name = table_data.get('name')
                    if not table_name:
                        results.append({
                            "status": "error",
                            "message": "缺少必需的表名称字段 'name'"
                        })
                        continue
                    table_lang = table_data.get('lang', lang)
                else:
                    results.append({
                        "status": "error",
                        "message": f"不支持的数据类型: {type(table_data)}"
                    })
                    continue
                
                # 添加子表
                result = base.add_table(table_name, lang=table_lang)
                results.append({
                    "status": "success",
                    "table_name": table_name,
                    "result": result
                })
            except Exception as e:
                table_name = table_data if isinstance(table_data, str) else table_data.get('name', 'unknown')
                results.append({
                    "status": "error",
                    "table_name": table_name,
                    "message": str(e)
                })
        return {"batch_results": results}
    
    elif operation == 'rename':
        results = []
        for table_data in tables_data:
            try:
                # 获取必需字段
                old_name = table_data.get('old_name')
                new_name = table_data.get('new_name')
                
                if not old_name or not new_name:
                    results.append({
                        "status": "error", 
                        "message": f"缺少必需的字段: {'' if old_name else 'old_name'} {'' if new_name else 'new_name'}"
                    })
                    continue
                
                # 重命名表
                result = base.rename_table(old_name, new_name)
                results.append({
                    "status": "success",
                    "old_name": old_name,
                    "new_name": new_name,
                    "result": result
                })
            except Exception as e:
                old_name = table_data.get('old_name', 'unknown')
                results.append({
                    "status": "error",
                    "old_name": old_name,
                    "message": str(e)
                })
        return {"batch_results": results}
    
    elif operation == 'delete':
        results = []
        for table_name in tables_data:
            try:
                result = base.delete_table(table_name)
                results.append({
                    "status": "success",
                    "table_name": table_name,
                    "result": result
                })
            except Exception as e:
                results.append({
                    "status": "error",
                    "table_name": table_name,
                    "message": str(e)
                })
        return {"batch_results": results}
    
    else:
        return {
            "status": "error",
            "message": f"不支持的操作类型: {operation}，支持的操作有: get, add, rename, delete"
        }

@mcp.tool
def batch_row_operations(operation: str, table_name: str, data: list = None, view_name: str = None, 
                        start: int = None, limit: int = None, apply_default: bool = False, 
                        api_token: str = None) -> dict:
    """
    行数据批量操作函数，可执行多种行操作
    
    Args:
        operation: 要执行的操作类型，支持以下几种:
            - 'list': 列出行数据
            - 'get': 获取指定行数据
            - 'append': 添加行
            - 'update': 更新行
            - 'delete': 删除行
        table_name: 子表名称或id
        data: 根据不同操作有不同格式:
            - 'list': 不需要此参数
            - 'get': 行ID列表，如 ["行ID1", "行ID2"]
            - 'append': 行数据列表，每个元素为一行数据的字典
            - 'update': 行更新数据列表，每个元素包含row_id和row字段
            - 'delete': 行ID列表
        view_name: 视图名称或id，仅在operation='list'时有效
        start: 索引的起始位置，仅在operation='list'时有效
        limit: 数据的显示数量，最大返回1000行，仅在operation='list'时有效
        apply_default: 是否使用表格列中设置的默认值，仅在operation='append'时有效
        api_token: SeaTable API令牌，可选，未提供时使用全局配置
    
    Returns:
        操作结果，具体结构根据操作类型而定
        
    Examples:
        # 列出行数据
        rows = batch_row_operations('list', '表1', view_name='默认视图', limit=100)
        
        # 获取多行数据
        rows = batch_row_operations('get', '表1', data=['row1', 'row2'])
        
        # 批量添加行
        result = batch_row_operations('append', '表1', data=[
            {"列1": "值1", "列2": "值2"},
            {"列1": "值3", "列2": "值4"}
        ])
        
        # 批量更新行
        result = batch_row_operations('update', '表1', data=[
            {"row_id": "row1", "row": {"列1": "新值1"}},
            {"row_id": "row2", "row": {"列2": "新值2"}}
        ])
        
        # 批量删除行
        result = batch_row_operations('delete', '表1', data=['row1', 'row2'])
    """
    base = authenticate_seatable(api_token)
    
    # 根据操作类型分发不同的处理逻辑
    if operation == 'list':
        return base.list_rows(table_name, view_name=view_name, start=start, limit=limit)
    
    elif operation == 'get':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供行ID列表"}
        
        results = {}
        for row_id in data:
            try:
                row_data = base.get_row(table_name, row_id)
                results[row_id] = {
                    "status": "success",
                    "data": row_data
                }
            except Exception as e:
                results[row_id] = {
                    "status": "error",
                    "message": str(e)
                }
        return results
    
    elif operation == 'append':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供行数据列表"}
        
        return base.batch_append_rows(table_name, data, apply_default=apply_default)
    
    elif operation == 'update':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供行更新数据列表"}
        
        try:
            # 确保数据格式正确
            rows_data = []
            for item in data:
                if isinstance(item, dict) and "row_id" in item and "row" in item:
                    rows_data.append(item)
                else:
                    return {"status": "error", "message": "数据格式错误，每个元素需包含row_id和row字段"}
            
            return base.batch_update_rows(table_name, rows_data)
        except Exception as e:
            return {"status": "error", "message": str(e)}
    
    elif operation == 'delete':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供行ID列表"}
        
        return base.batch_delete_rows(table_name, data)
    
    else:
        return {
            "status": "error",
            "message": f"不支持的操作类型: {operation}，支持的操作有: list, get, append, update, delete"
        }

@mcp.tool
def batch_column_operations(operation: str, table_name: str, data: list = None, view_name: str = None, 
                           column_type: str = None, api_token: str = None) -> dict:
    """
    列数据批量操作函数，可执行多种列操作
    
    Args:
        operation: 要执行的操作类型，支持以下几种:
            - 'list': 列出所有列
            - 'get_by_name': 通过名称获取列
            - 'get_by_type': 通过类型获取列
            - 'insert': 插入/追加列
            - 'rename': 重命名列
            - 'move': 移动列
            - 'modify_type': 修改列类型
            - 'add_options': 添加选项(单选/多选列)
            - 'delete': 删除列
        table_name: 子表名称或id
        data: 根据不同操作有不同格式:
            - 'list': 不需要此参数
            - 'get_by_name': 列名称列表，如 ["列1", "列2"]
            - 'get_by_type': 不需要此参数(使用column_type参数)
            - 'insert': 列定义列表，每个元素包含name, type等字段
            - 'rename': 重命名信息列表，每个元素包含key, new_name字段
            - 'move': 移动信息列表，每个元素包含key, target_key字段
            - 'modify_type': 类型修改列表，每个元素包含key, new_type字段
            - 'add_options': 选项添加列表，每个元素包含column, options字段
            - 'delete': 列key列表
        view_name: 视图名称或id，仅在operation='list'时有效
        column_type: 列类型，仅在operation='get_by_type'时有效
        api_token: SeaTable API令牌，可选，未提供时使用全局配置
    
    列类型参考 (用于insert和modify_type操作):
        NUMBER - 数字
        TEXT - 文本
        LONG_TEXT - 长文本
        CHECKBOX - 勾选
        DATE - 日期时间
        SINGLE_SELECT - 单选
        MULTIPLE_SELECT - 多选
        IMAGE - 图片
        FILE - 文件
        COLLABORATOR - 协作人
        LINK - 链接其他记录
        FORMULA - 公式
        CREATOR - 创建者
        CTIME - 创建时间
        LAST_MODIFIER - 修改者
        MTIME - 修改时间
        GEOLOCATION - 地址
        AUTO_NUMBER - 自动序号
        URL - 链接
    
    Returns:
        操作结果，具体结构根据操作类型而定
        
    Examples:
        # 列出所有列
        columns = batch_column_operations('list', '表1')
        
        # 通过名称获取多个列
        columns = batch_column_operations('get_by_name', '表1', data=['列1', '列2'])
        
        # 通过类型获取列
        columns = batch_column_operations('get_by_type', '表1', column_type='TEXT')
        
        # 批量插入列
        result = batch_column_operations('insert', '表1', data=[
            {"name": "文本列", "type": "TEXT"},
            {"name": "数字列", "type": "NUMBER"},
            {"name": "日期列", "type": "DATE"},
            {"name": "链接列", "type": "LINK", "data": {"table": "Table1", "other_table": "Test_User"}}
        ])
        
        # 批量重命名列
        result = batch_column_operations('rename', '表1', data=[
            {"key": "列key1", "new_name": "新列名1"},
            {"key": "列key2", "new_name": "新列名2"}
        ])
        
        # 批量移动列
        result = batch_column_operations('move', '表1', data=[
            {"key": "列key1", "target_key": "目标列key1"},
            {"key": "列key2", "target_key": "目标列key2"}
        ])
        
        # 批量修改列类型
        result = batch_column_operations('modify_type', '表1', data=[
            {"key": "列key1", "new_type": "NUMBER"},
            {"key": "列key2", "new_type": "TEXT"}
        ])
        
        # 批量添加选项
        result = batch_column_operations('add_options', '表1', data=[
            {
                "column": "单选列1", 
                "options": [{"name": "选项1", "color": "#aaa", "textColor": "#000000"}]
            }
        ])
        
        # 批量删除列
        result = batch_column_operations('delete', '表1', data=['列key1', '列key2'])
    """
    base = authenticate_seatable(api_token)
    
    # 根据操作类型分发不同的处理逻辑
    if operation == 'list':
        return base.list_columns(table_name, view_name=view_name)
    
    elif operation == 'get_by_name':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供列名列表"}
        
        results = {}
        for column_name in data:
            try:
                column_info = base.get_column_by_name(table_name, column_name)
                results[column_name] = {
                    "status": "success",
                    "data": column_info
                }
            except Exception as e:
                results[column_name] = {
                    "status": "error",
                    "message": str(e)
                }
        return results
    
    elif operation == 'get_by_type':
        if not column_type:
            return {"status": "error", "message": "column_type参数为必填项，需要指定列类型"}
        
        try:
            # 将字符串转换为ColumnTypes枚举值
            column_type_value = getattr(ColumnTypes, column_type)
            return base.get_columns_by_type(table_name, column_type_value)
        except Exception as e:
            return {"status": "error", "message": str(e)}
    
    elif operation == 'insert':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供列定义列表"}
        
        results = []
        for column in data:
            try:
                # 获取必需字段
                column_name = column.get('name')
                column_type = column.get('type')
                
                if not column_name or not column_type:
                    results.append({
                        "status": "error", 
                        "message": f"缺少必需的字段: {'' if column_name else 'name'} {'' if column_type else 'type'}"
                    })
                    continue
                    
                # 获取可选字段
                column_key = column.get('key')
                column_data = column.get('data')
                
                # 将字符串转换为ColumnTypes枚举值
                column_type_value = getattr(ColumnTypes, column_type)
                
                # 插入列
                result = base.insert_column(table_name, column_name, column_type_value, 
                                           column_key=column_key, column_data=column_data)
                results.append({
                    "status": "success",
                    "column_name": column_name,
                    "result": result
                })
            except Exception as e:
                results.append({
                    "status": "error",
                    "column_name": column.get('name', 'unknown'),
                    "message": str(e)
                })
        return {"batch_results": results}
    
    elif operation == 'rename':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供重命名信息列表"}
        
        results = []
        for item in data:
            try:
                # 获取必需字段
                column_key = item.get('key')
                new_name = item.get('new_name')
                
                if not column_key or not new_name:
                    results.append({
                        "status": "error", 
                        "message": f"缺少必需的字段: {'' if column_key else 'key'} {'' if new_name else 'new_name'}"
                    })
                    continue
                
                # 重命名列
                result = base.rename_column(table_name, column_key, new_name)
                results.append({
                    "status": "success",
                    "column_key": column_key,
                    "result": result
                })
            except Exception as e:
                results.append({
                    "status": "error",
                    "column_key": item.get('key', 'unknown'),
                    "message": str(e)
                })
        return {"batch_results": results}
    
    elif operation == 'move':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供移动信息列表"}
        
        results = []
        for item in data:
            try:
                # 获取必需字段
                column_key = item.get('key')
                target_key = item.get('target_key')
                
                if not column_key or not target_key:
                    results.append({
                        "status": "error", 
                        "message": f"缺少必需的字段: {'' if column_key else 'key'} {'' if target_key else 'target_key'}"
                    })
                    continue
                
                # 移动列
                result = base.move_column(table_name, column_key, target_key)
                results.append({
                    "status": "success",
                    "column_key": column_key,
                    "result": result
                })
            except Exception as e:
                results.append({
                    "status": "error",
                    "column_key": item.get('key', 'unknown'),
                    "message": str(e)
                })
        return {"batch_results": results}
    
    elif operation == 'modify_type':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供类型修改列表"}
        
        results = []
        for item in data:
            try:
                # 获取必需字段
                column_key = item.get('key')
                new_type = item.get('new_type')
                
                if not column_key or not new_type:
                    results.append({
                        "status": "error", 
                        "message": f"缺少必需的字段: {'' if column_key else 'key'} {'' if new_type else 'new_type'}"
                    })
                    continue
                
                # 将字符串转换为ColumnTypes枚举值
                column_type_value = getattr(ColumnTypes, new_type)
                
                # 修改列类型
                result = base.modify_column_type(table_name, column_key, column_type_value)
                results.append({
                    "status": "success",
                    "column_key": column_key,
                    "result": result
                })
            except Exception as e:
                results.append({
                    "status": "error",
                    "column_key": item.get('key', 'unknown'),
                    "message": str(e)
                })
        return {"batch_results": results}
    
    elif operation == 'add_options':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供选项添加列表"}
        
        results = []
        for item in data:
            try:
                # 获取必需字段
                column = item.get('column')
                options = item.get('options')
                
                if not column or not options:
                    results.append({
                        "status": "error", 
                        "message": f"缺少必需的字段: {'' if column else 'column'} {'' if options else 'options'}"
                    })
                    continue
                
                # 添加选项
                result = base.add_column_options(table_name, column, options)
                results.append({
                    "status": "success",
                    "column": column,
                    "result": result
                })
            except Exception as e:
                results.append({
                    "status": "error",
                    "column": item.get('column', 'unknown'),
                    "message": str(e)
                })
        return {"batch_results": results}
    
    elif operation == 'delete':
        if not data:
            return {"status": "error", "message": "data参数为必填项，需要提供列key列表"}
        
        results = []
        for column_key in data:
            try:
                result = base.delete_column(table_name, column_key)
                results.append({
                    "status": "success",
                    "column_key": column_key,
                    "result": result
                })
            except Exception as e:
                results.append({
                    "status": "error",
                    "column_key": column_key,
                    "message": str(e)
                })
        return {"batch_results": results}
    
    else:
        return {
            "status": "error",
            "message": f"不支持的操作类型: {operation}，支持的操作有: list, get_by_name, get_by_type, insert, rename, move, modify_type, add_options, delete"
        }

@mcp.tool
def query(sql: str, api_token: str = None) -> list:
    """
    使用SQL语句查询一个base
    Args:
        sql: 要执行的SQL语句
        api_token: SeaTable API令牌，可选，未提供时使用全局配置
    Returns:
        查询结果列表，默认最多返回100条结果
    Notes:
        如果需要返回更多结果，请在SQL语句中添加LIMIT参数
    """
    base = authenticate_seatable(api_token)
    return base.query(sql)

@mcp.tool
def set_api_token(api_token: str) -> dict:
    """
    设置全局API令牌
    Args:
        api_token: SeaTable API令牌
    Returns:
        设置结果
    """
    global GLOBAL_API_TOKEN
    GLOBAL_API_TOKEN = api_token
    
    # 保存到配置文件
    config = {"api_keys": {"seatable": api_token}}
    save_config(config)
    
    return {"status": "success", "message": "API令牌已设置并保存到配置文件"}


# 主程序入口
if __name__ == "__main__":
    # 从配置文件加载API令牌
    GLOBAL_API_TOKEN = get_api_key("seatable")
    if not GLOBAL_API_TOKEN:
        print("警告: SeaTable API令牌未在配置文件中设置。请使用set_api_token工具设置令牌。")

    # print(GLOBAL_API_TOKEN)

    # 启动FastMCP服务
    mcp.run()






